×
☰ See All Chapters

Diamond Operator with Anonymous Inner Class

From java 9 we can use diamond operator for anonymous inner classes with optional type parameter.  Diamond operator can be empty or can be with type parameter. If type parameter is not specified then compiler of Java 9 will auto infers the type.

diamond-operator-with-anonymous-inner-class-0
 

Using diamond operator with anonymous inner classes is not allowed in java 8 and below versions.

diamond-operator-with-anonymous-inner-class-1
 

package com.java4coding.test;

interface Demo<T> {

        abstract void sayHello();

}

public class Test {  

    public static void main(String[] args) {  

            Demo<String> demo = new Demo<>() {

           public void  sayHello() {  

                  System.out.println("Hello");  

            }  

        };    

        demo.sayHello();  

    }  

}

We can specify type parameter as shown below:

package com.java4coding.test;

interface Demo<T> {

        abstract void sayHello();

}

public class Test {  

    public static void main(String[] args) {  

            Demo<String> demo = new Demo<String>() {

           public void  sayHello() {  

                  System.out.println("Hello");  

            }  

        };    

        demo.sayHello();  

    }  

}

 


All Chapters
Author